package com.crm.sys.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.crm.customers.dao.CustomerDao;
import com.crm.customers.model.CustomerInfo;
import com.crm.im.core.model.Message;
import com.crm.sys.dao.SysDao;
import com.crm.sys.dao.SysMessageDao;
import com.crm.sys.model.Announcement;
import com.crm.sys.model.CallLog;
import com.crm.sys.model.City;
import com.crm.sys.model.Configure;
import com.crm.sys.model.ConfigureItem;
import com.crm.sys.model.Department;
import com.crm.sys.model.Log;
import com.crm.sys.model.Province;
import com.crm.sys.model.Recordings;
import com.crm.sys.model.Role;
import com.crm.sys.model.RoleItme;
import com.crm.sys.model.RoleProduct;
import com.crm.sys.model.SysMessage;
import com.crm.sys.model.SysTerm;
import com.crm.sys.model.TokenPackage;
import com.crm.sys.model.UserHistoryMessage;
import com.crm.sys.service.PushService;
import com.crm.sys.service.SysService;
import com.crm.user.dao.UserDao;
import com.crm.user.model.UserInfo;
import com.crm.user.service.UserService;
import com.crm.util.Constants;
import com.crm.util.CrmUtil;
import com.crm.util.HttpRequester;
import com.crm.util.Pager;
import com.google.common.base.Splitter;
import com.wjyup.coolq.util.CQSDK;
import com.wjyup.coolq.util.ConfigCache;
@Service("sysService")
public class SysServiceImpl implements SysService {
	@Autowired
	private SysDao sysDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private SysMessageDao  sysMessageDao; 
	@Autowired
	private CustomerDao customerDao;
	@Autowired
	private PushService pushService;
	@Autowired
	private UserService userService;
	
	
	@Override
	public List<Province> getProvinceList() {
		return sysDao.getProvinceList();
	}

	@Override
	public List<City> getCityListByProId(int proid) {
		City city = new City();
		city.setProvince(proid);
		return sysDao.getCityListByProId(city);
	}

	@Override
	public Configure getConfigureByName(String code) {
		Configure cf = new Configure();
		cf.setCode(code);
		Configure  c = sysDao.getConfigureByName(cf) ;
		if(c!=null&&c.getId()>0){
			ConfigureItem cfi = new ConfigureItem();
			cfi.setValue(null);
			cfi.setCid(c.getId());
			cfi.setPid(0L);
			List<ConfigureItem>  result =  sysDao.getConfigureItemById(cfi);
			c.setItem(result);
		}
		return c;
	}

	@Override
	public ConfigureItem getConfigureItemByValue(String value,String code){
		Configure cf = new Configure();
		cf.setCode(code);
		Configure  c = sysDao.getConfigureByName(cf);
		ConfigureItem cfi = new ConfigureItem();
		cfi.setValue(value);
		cfi.setCid(c.getId());
		//cfi.setPid(0L);
		List<ConfigureItem>  result =  sysDao.getConfigureItemById(cfi);
		return result!=null&&result.size()>0?result.get(0):null;
	}

	@Override
	public List<Department> getDepartmentAll() {
		 //顶级部门 父ID为0
		return  getDepartmentByPid(0L);
	}
	

	@Override
	public List<Department> getAllDeptmentByPid(Long pid) {
		List<Department> list = new ArrayList<Department>();
		Department dt = new Department();
		dt.setId(pid);
		dt.setParentid(null);
		dt = sysDao.getDepartmentById(dt);
		List<Department> dtlist = getDepartmentByPid(pid);
		if (dtlist != null && dtlist.size() > 0) {
			dt.setDepList(dtlist);
		}
		list.add(dt);
		return list;
	}
	
	@Override
	public List<Department> getDepartmentListAll(Department d) {
		return   sysDao.getDepartmentAll(d);
	}
	/**
	 * 递归调用部门信息
	 * @param pid
	 * @return
	 */
	private List<Department> getDepartmentByPid(Long pid){
		     Department  dept = new Department();
		     dept.setParentid(pid);
		     List<Department>  list = sysDao.getDepartmentAll(dept) ;
		     for(Department d:list){
			    	 UserInfo u =new UserInfo();
			    	 u.setDeptid(d.getId());
		   			 List<UserInfo> userlist=userDao.getUserInfoListByDeptid(u);
		   			 d.setUserlist(userlist); 
		   			 d.setCount(userlist.size());
		    	     d.setDepList(getDepartmentByPid(d.getId()));
		     }
		   return list;
	}

	@Override
	public Department getDepartmentById(Long id) {
		  Department  dept = new Department();
		  dept.setId(id);
		  dept.setParentid(null);
		return sysDao.getDepartmentById(dept);
	}

	@Override
	public Pager getRoleList(Role role, int pageNo, int pageSize) {
			role.setStartsize(((pageNo-1)*pageSize));
			role.setEndsize(pageSize);
			List<Role>  list = sysDao.getRoleList(role);
		    Pager  pager = new Pager();
			pager.setPageNo(pageNo);
			pager.setPageSize(pageSize);
			pager.setResultList(list);
		    return pager;
	}

	@Override
	public int saveRole(Role role, String productcategorys) {
		 int results=1;
		Role result=sysDao.insertRole(role);
		Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(productcategorys);
        for (String idStr : splitStr) {
        	RoleProduct roleproduct=new RoleProduct();
        	roleproduct.setRid(result.getId());
        	roleproduct.setProductcategory(Integer.parseInt(idStr));
        	   sysDao.insertRoleProduct(roleproduct);
        }
		return results;
	}

	@Override
	public Role getRoleByid(Long id) {
		Role roleParam = new Role();
		roleParam.setId(id);
		Role role=sysDao.getRoleByid(roleParam);
		RoleProduct rolep = new RoleProduct();
		rolep.setId(role.getId());
		List<RoleProduct> rp=sysDao.getRoleProductByid(rolep);
		role.setRplist(rp);
		return role;
	}

	@Override
	public int updateRole(Role role, String productcategorys) {
		int result=1;
    	sysDao.deleteRoleProduct(role);
    	sysDao.updateRole(role);
		Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(productcategorys);
		 for (String idStr : splitStr) {
	        	
			 RoleProduct roleproduct=new RoleProduct();
	        	roleproduct.setRid(role.getId());
	        	roleproduct.setProductcategory(Integer.parseInt(idStr));
	        	sysDao.insertRoleProduct(roleproduct);
	        }
		
		return result;
	}

	@Override
	public Pager getSysTermList(SysTerm systerm, int pageNo, int pageSize) {
		 systerm.setStartsize(((pageNo-1)*pageSize));
		 systerm.setEndsize(pageSize);
		 List<SysTerm>  list = sysDao.getSysTermList(systerm);
	     Pager  pager = new Pager();
		 pager.setPageNo(pageNo);
		 pager.setPageSize(pageSize);
		 pager.setResultList(list);
	     return pager;
	}

	@Override
	public int insertSysTerm(SysTerm systerm) {
		sysDao.insertSysTerm(systerm);
		int result=1;
		return result;
	}

	@Override
	public SysTerm getSysTermByid(Long id) {
		SysTerm term = new SysTerm();
		term.setId(id);
		return sysDao.getSysTermByid(term);
	}

	@Override
	public int updateSysTerm(SysTerm systerm) {
		return sysDao.updateSysTerm(systerm);
	}

	@Override
	public int updateRoleState(Long id, int str) {
		int result=1;
		Role role = new Role();
		role.setId(id);
		if(str==1){
			role.setState(0);
		}else{
			role.setState(1);
		}
		result = sysDao.updateRoleState(role);
		return result;
	}

	@Override
	public List<SysTerm> getSysTermBound(SysTerm systerm,int rid) {
		return sysDao.getSysTermBound(rid);
	}

	@Override
	public int saveSysTermBound(String rid, String tids) {
		
		int result=1;
		Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(tids);
		RoleItme   ri = new RoleItme();
		ri.setRid(Integer.parseInt(rid));
		sysDao.deleteSysTermBound(ri);
		 for (String idStr : splitStr) {
			 ri = new RoleItme();
			 ri.setRid(Integer.parseInt(rid));
			 ri.setTid(Integer.parseInt(idStr));
			 sysDao.updateSysTermBound(ri);
	        }
		return result;
	}

	@Override
	public List<SysTerm> getMune(Long uid) {
		 List<SysTerm>  list = getMuneByPid(0L,uid);
		  return list;
	}
	
	private  List<SysTerm> getMuneByPid(Long pid,Long uid){
		SysTerm term = new SysTerm();
		term.setPid(pid);
		term.setCreateuser(uid);
		List<SysTerm>  list = sysDao.getMuneAll(term) ;
	     for(SysTerm s:list){
	    	     s.setSubList(getMuneByPid(s.getId(),uid));
	     }
	   return  list;
	}
	
	
	@Override
	public List<SysTerm> getRoleMenu(Long rid) {
		 List<SysTerm>  list = getMuneByPidAndRid(0L,rid);
		  return list;
	}
     /**
      * 根据权限ID查询
      * @param pid
      * @param rid
      * @return
      */
	private  List<SysTerm> getMuneByPidAndRid(Long pid,Long rid){
		SysTerm term = new SysTerm();
		term.setPid(pid);
		term.setRid(rid);
		List<SysTerm>  list = sysDao.getMenuByRid(term) ;
	     for(SysTerm s:list){
	    	 List<SysTerm>  sublist = getMuneByPidAndRid(s.getId(),rid);
	    	 if(sublist!=null&&sublist.size()>0){
	    		 s.setChecked(0);
	    	 }else{
	    		 s.setChecked(1);
	    	 }
	    	 s.setSubList(sublist);
	     }
	   return  list;
	}

	@Override
	public List<SysTerm> getRoleMune(Long uid, String url) {
		SysTerm  term = new SysTerm();
		term.setCreateuser(uid);
		term.setUrl(url);
		return sysDao.getRoleMune(term);
	}

	@Override
	public City getCityContantsProvince(String name) {
		return sysDao.getCityContantsProvince(name);
	}

	@Override
	public Province getProvinceByName(String name) {
		return sysDao.getProvinceByName(name);
	}

	@Override
	public List<Announcement> getAnnouncements() {
		return sysDao.getAnnouncements();
	}

	/*@Override
	public Pager getUserandCustomerList(CustomerInfo info, int pageNo,
			int pageSize) {
		 List<CustomerInfo>  list = customerDao.getCustomerInfoList(info, pageNo, pageSize);
		    Pager  pager = new Pager();
			pager.setPageNo(pageNo);
			pager.setPageSize(pageSize);
			pager.setResultList(list);
		    return pager;
	}*/

	@Override
	public int saveCustomerCreatuserUpdate(String ids, String uid,Long infoid) {
		int result=0;
		/*Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(ids);
		
	 for (String idStr : splitStr) {
		 CustomerInfo info =new CustomerInfo();
		 info.setId(Long.valueOf(idStr));
		 info.setCreateuser(uid);
		 result=customerDao.updateCustomerCreateUser(info);
		//添加操作日志
		 if(result!=0){
			 Log log = new Log();
				log.setContentid(info.getId());
				log.setCategory(Constants.LOGCATEGORY.ONE);
				UserInfo ui= userDao.getUserInfo(Long.valueOf(uid));
				log.setDescription("分配客户给"+ui.getName());
				log.setCreateuser(info.getCreateuser());
				log.setUid(infoid);
				sysDao.insertLog(log);
		 }
			
       }*/
	
	return result;
	}

	@Override
	public int saveLoginfo(Log log) {
		
	 sysDao.insertLog(log);
	 return 1;
	}

	@Override
	public List<Log> getLogList(Log log, int pageNo, int pageSize) {
		log.setStartsize((pageNo-1)*pageSize);
		log.setEndsize(pageSize);
		List<Log> list = sysDao.getLogList(log);
		return list;
	}

	@Override
	public List<SysMessage> getMessageList(SysMessage ms) {
		return sysMessageDao.getMessageList(ms);
	}

	@Override
	public int getMessageCount(SysMessage ms) {
		return sysMessageDao.getMessageCount(ms);
	}

	@Override
	public int insertMessage(SysMessage ms) {
		return sysMessageDao.insertMessage(ms);
	}

	@Override
	public int updateMessageState(SysMessage ms) {
		return sysMessageDao.updateMessageState(ms);
	}

	@Override
	public ConfigureItem getCategoryByid(String value, String code) {
		Configure cf = new Configure();
		cf.setCode(code);
		Configure  c = sysDao.getConfigureByName(cf);
		ConfigureItem cfi = new ConfigureItem();
		cfi.setValue(value);
		cfi.setCid(c.getId());
		List<ConfigureItem>  result =  sysDao.getConfigureItemById(cfi);
		return result!=null&&result.size()>0?result.get(0):null;
	}

	@Override
	public void pushRemind() {
		// TODO Auto-generated method stub
		List<CustomerInfo>  list = customerDao.getAllRemindCustomer();
		if(list!=null&&list.size()>0){
			for(CustomerInfo info:list){
				Message message = new Message();
				message.setType("2");
				message.setContent("有"+ info.getRowsCount()+"条客户资源需要赶紧联系啊！还不联系就掉公共资源库了！"+Constants.ROBOTNAME+"已经给你把需要联系的客户资源标成红色了，赶紧去联系下吧！");
				message.setReceiver(String.valueOf(info.getUid()));
				pushService.pushMsgToUser(message); 
			}
		}
		
	}

	@Override
	public  List<UserHistoryMessage> getUserHistoryMessage(UserHistoryMessage ms, int pageNo,
			int pageSize) {
		ms.setStartsize((pageNo-1)*pageSize);
		ms.setEndsize(pageSize);
		return sysMessageDao.getMessageList(ms);
	}

	@Override
	public int insertAllTransLog(Log log) {
		return sysDao.insertAllTransLog(log);
	}

	@Override
	public int insertLog(Log log) {
		return sysDao.insertLog(log);
	}

	@Override
	public void pushCopyUserToQQ() {
		List<Log>  list = sysDao.getCopyCount();
		if(list!=null&&list.size()>0){
			for(Log log:list){
				for(Long qq:ConfigCache.MANAGER_QQ){
					 CQSDK.sendPrivateMsg(qq.toString(), log.getCreateuserName()+"一分钟内复制次数已经达到"+log.getRowsCount()+"次");
				}
			}
		} 
	}

	@Override
	public int addDepartment(Department d) {
		return sysDao.addDepartment(d);
	}

	@Override
	public List<Configure> getConfigureList(int pageNo, int pageSize) {
		Configure c = new Configure();
		c.setStartsize((pageNo-1)*pageSize);
		c.setEndsize(pageSize);
		return sysDao.getConfigureList(c);
	}

	@Override
	public List<ConfigureItem> getConfigureItemList(ConfigureItem ci, int pageNo, int pageSize) {
		ci.setStartsize((pageNo-1)*pageSize);
		ci.setEndsize(pageSize);
		return sysDao.getConfigureItemList(ci);
	}

	@Override
	public Integer getMaxOrderNumber(ConfigureItem ci) {
		return sysDao.getMaxOrderNumber(ci);
	}

	@Override
	public int addConfigure(Configure c) {
		return sysDao.addConfigure(c);
	}

	@Override
	public int addConfigureItem(ConfigureItem ci) {
		// TODO Auto-generated method stub
		return sysDao.addConfigureItem(ci);
	}

	@Override
	public int deleteConfigure(Configure c) {
		
		//因为不管配置表详情表的子列表是否还有子列表，cid都是配置表的id，所以直接根据cid判断就行了
		ConfigureItem ci = new ConfigureItem();
		ci.setCid(c.getId());
		sysDao.deleteConfigureItem(ci);
		return sysDao.deleteConfigure(c);
	}
	
	

	@Override
	public int deleteConfigureItem(ConfigureItem ci) {
		return sysDao.deleteConfigureItem(ci);
	}

	@Override
	public int updateConfigure(Configure c) {
		return sysDao.updateConfigure(c);
	}

	@Override
	public int updateConfigureItem(ConfigureItem ci) {
		return sysDao.updateConfigureItem(ci);
	}

	@Override
	public int deleteDepartment(Long id) {
		sysDao.deleteDepartment(id);
		deleteSonDept(id);
		return 0;
	}
	
	//循环删除子部门
	public void deleteSonDept(Long parentid){
		List<Department> list = sysDao.getDeptListByPid(parentid);
		for (Department d : list) {
			sysDao.deleteDepartment(d.getId());
			deleteSonDept(d.getId());
		}
	}

	@Override
	public int updateDepartment(Department d) {
		return sysDao.updateDepartment(d);
	}

	@Override
	public List<Long> getAllDeptmentidByPid(Long pid) {
		//要递归循环所有的子部门
		List<Long> list = new ArrayList<Long>();
		list.add(pid);
		list = getdeptsonidbypid(pid,list);
		return list;
	}
	
	public List<Long> getdeptsonidbypid(Long pid,List<Long> list) {
		List<Department> dtlist = sysDao.getDeptListByPid(pid);
		if (dtlist != null && dtlist.size() > 0){
			for (Department d : dtlist) {
				list.add(d.getId());
				list = getdeptsonidbypid(d.getId(),list);
			}
		}
		return list;
	}

	@Override
	public List<CallLog> getCallLogList(CallLog cl, int pageNo, int pageSize) {
		cl.setStartsize(((pageNo-1)*pageSize));
		cl.setEndsize(pageSize);
		return sysDao.getCallLogList(cl);
	}
	

	@Override
	public int saveCallLog(CallLog cl) {
	   //查询是否已经生成呼叫日志，否则生成日志
		int  result = sysDao.getCallLogCountByCode(cl);
		if(result<1) {
			sysDao.insertCallLog(cl);
		}
		return result;
	}

	@Override
	public List<CallLog> getUpdCallLogList() {
		return sysDao.getUpdCallLogList();
	}

	@Override
	public int updateCallLog(CallLog cl) {
		return sysDao.updateCallLog(cl);
	}

	
	private String refreshAccessToken(String refreshToken, String requestUrl) throws Exception {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("client_id",Constants.CALLCENTER.get("client_id")));
        params.add(new NameValuePair("grant_type", "refresh_token"));
        params.add(new NameValuePair("client_secret", Constants.CALLCENTER.get("client_secret")));
        params.add(new NameValuePair("refresh_token", refreshToken));
        params.add(new NameValuePair("redirect_uri", requestUrl));

        NameValuePair[] pairs = new NameValuePair[params.size()];

        return HttpRequester.post("http://oauth.aliyun.com/v1/token", params.toArray(pairs));
    }
	
	@Override
	public void updatecallLogTime() {
		UserInfo  uinfo = userService.getUserInfo(1L);
		if(StringUtils.isNotEmpty(uinfo.getAccessToken())) {
			
			
			List<CallLog>   updList = getUpdCallLogList();
			if(updList!=null&&updList.size()>0) {
				String request ="{\"ContactId\":'{contactId}',\"instanceId\":\""+Constants.CALLCENTER.get("instanceId")+"\"}";
			   int j =0;
				for(CallLog  clog:updList) {
					 //   String request = "{'InstanceId':'"+Constants.CALLCENTER.get("instanceId")+"','ContactId':'2012934297'}";
			           String token = uinfo.getAccessToken();
			         //String token =  (String)httpServletRequest.getSession().getAttribute("tokenid");
			    
			            try {
			            	   TokenPackage   tokenPackage =  TokenPackage.parse(token);
				                if(j==0 || tokenPackage==null  || tokenPackage.isExpire()) {
				                	    String accessToken = refreshAccessToken(tokenPackage.getRefreshToken(),"/aliyun/ccc/api");
				                	    try {
							                tokenPackage = TokenPackage.parse(accessToken);
							            } catch (Exception e) {
							            } 
				                	    if(tokenPackage!=null&&StringUtils.isNotEmpty(tokenPackage.getRefreshToken())) {
							  		          UserInfo uinfoTwo = new UserInfo();
							  		          uinfoTwo.setUid(uinfo.getUid());
							  		           uinfoTwo.setAccessToken(accessToken);
							  		           userService.updateUserInfo(uinfoTwo); 
				                	    }   
				                }  
				                String listRecord =  CrmUtil.invokeApiByBearerToken(tokenPackage.getAccessToken(), "ListRecordingsByContactId", request.replace("{contactId}", clog.getContactId())); 
				  		        if(StringUtils.isNotEmpty(listRecord)) {
				  		      	    Recordings recordings = JSONObject.parseObject(listRecord, Recordings.class);
						  		    try {
						  				     
						  			}catch(Exception e) {
						  				e.printStackTrace();
						  			}  
				  		        }
				         } catch (Exception e) {
				         }   
			            j++;
				}
				  
			} 
		}
		
	}

	@Override
	public Map<String, Object> getCallLogData(CallLog cl) {
		 Map<String, Object> map = new HashMap<String, Object>();
		 int  total = sysDao.getCallLogData(cl);
		 cl.setTime(1);
		 int  yxtotal = sysDao.getCallLogData(cl);
		 int  timetotal =  sysDao.getCallLogTimeTotal(cl);
		 map.put("timetotal", jsTime(timetotal));
		 map.put("total", total);
		 map.put("yxtotal", yxtotal);
	
		return map;
	}

	 private String jsTime(int timetotal) {
		 String str="";
		 if(timetotal>59) {
			 int minutes = timetotal / 60;   
		     int remainingSeconds = timetotal % 60;   
		     if(minutes>0) {
		    	 str=minutes+"分钟";
		     }
		     if(remainingSeconds>0) {
		    	 str +=remainingSeconds+"秒";
		     }
		 }else {
			 str =timetotal+"秒";
		 }
		 return str;
	 }
	@Override
	public List<CallLog> getTimesUserCallLogList() {
		List<CallLog>  list = sysDao.getTimesUserCallLogList();
		if(list!=null&&list.size()>0) {
			 for(CallLog log:list) {
				 log.setStartTime(jsTime(log.getTime()));
			 } 
		} 
		return list;
	}


	
	
	
	
	
	
	/*@Override
	public List<CustomerInfo> getCustomerList(CustomerInfo info) {
		 List<CustomerInfo>  list = customerDao.getCustomerInfoAllList(info);
		 return list;
	}*/

	/*@Override
	public int saveCustomerCreatuserUpdateAll(List<CustomerInfo> list,
			String uid, Long infoid) {
		int result=0;
	 for (CustomerInfo infoStr : list) {
		 CustomerInfo info =new CustomerInfo();
		 info.setId(Long.valueOf(infoStr.getId()));
		 info.setCreateuser(uid);
		 result=customerDao.updateCustomerCreateUser(info);
		//添加操作日志
		 if(result!=0){
			 Log log = new Log();
				log.setContentid(info.getId());
				log.setCategory(Constants.LOGCATEGORY.ONE);
				UserInfo ui= userDao.getUserInfo(Long.valueOf(uid));
				log.setDescription("分配客户给"+ui.getName());
				log.setCreateuser(info.getCreateuser());
				log.setUid(infoid);
				sysDao.insertLog(log);
		 }
			
       }
	
	return result;
	}*/
	

}
